<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/3/4
 * Time: 9:52
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Memberb extends Base
{
    /**
     * 脖脸皮用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_bo_role = input('user_bo_role'); // 1 普通用户  2 自由创业者   3团员  4 团队长
            $user_bo_district_role = input('user_bo_district_role'); // 2 县级运营商  3 市级分公司  4 省级子公司
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间
            $_tzCode = input('tzCode');
            $_tyCode = input('tyCode');
            
            $where['user_rule'] = [['=', '3'], ['=', '2,3'], 'or'];
            $where['user_status'] = ['NEQ', 3];
            $where['user_private_worker'] = 1;
            
            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 脖脸皮系统等级
            if(isset($user_bo_role) && $user_bo_role != ''){
                $where['user_bo_role'] = $user_bo_role;
            }
            // 脖脸皮地区等级
            if(isset($user_bo_district_role) && $user_bo_district_role != ''){
                if($user_bo_district_role == 1){
                    $where['user_bo_district_role'] = $user_bo_district_role;
                }else{
                    $where['user_bo_district_role'] = ['LIKE', '%,' . $user_bo_district_role . ',%'];
                }
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
            if(isset($_tzCode) && $_tzCode != ''){
                $where['user_tz_code|user_up_tz_code|user_up_up_tz_code'] = ['LIKE', '%' . $_tzCode . '%'];
                $where['user_bo_role'] = 4;
            }
            if(isset($_tyCode) && $_tyCode != ''){
                $where['user_up_tz_code'] = ['LIKE', '%' . $_tyCode . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_u_user')->where($where)->count('user_id');
            $lists = Db::table('up_u_user')
                ->field('user_id, user_username, user_phone, user_bo_role, user_area_str, user_gender, 
                user_time, user_real_name, user_status, user_last_login, user_bo_district_role, user_tz_code,
                user_ty_code, user_up_tz_code, user_up_up_tz_code')
                ->where($where)
                ->order('user_time desc')
                ->page($Nowpage,$limits)
//                ->fetchSql(true)
                ->select();
//            print_r($lists);die;
            if($lists){
                foreach ($lists as $k => $v){
                    // 代理身份
                    if($v['user_bo_district_role'] == 1){
                        $district_role = '普通用户';
                        $lists[$k]['district_role'] = $district_role;
                    }else{
                        $district_role = '';
                        if(strpos($v['user_bo_district_role'], ',2,') !== false) $district_role .= '县级运营商';
                        if(strpos($v['user_bo_district_role'], ',3,') !== false) $district_role .= '，市级分公司';
                        if(strpos($v['user_bo_district_role'], ',4,') !== false) $district_role .= '，省级子公司';
                        $lists[$k]['district_role'] = trim($district_role, '，');
                    }
                    // 团员、团队长编号
                    if($v['user_bo_role'] == 3){
                        $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                        $tzCode = '/';
                    }elseif($v['user_bo_role'] == 4){
                        $tzCode = $v['user_tz_code'];
                        if(in_array($v['user_tz_code'], config('already_use'))){
                            $tyCode = '/';
                        }else{
                            $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                            $tzCode .= $v['user_up_tz_code'] == -1 ? '' : '_' . $v['user_up_tz_code'];
                            $tzCode .= $v['user_up_up_tz_code'] == -1 ? '' : '_' . $v['user_up_up_tz_code'];
                        }
                    }else{
                        $tyCode = '/';
                        $tzCode = '/';
                    }

                    $lists[$k]['tyCode'] = $tyCode;
                    $lists[$k]['tzCode'] = $tzCode;
                }
            }

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $this->assign([
            'province' => $province
        ]);
        return $this->fetch();
    }
    
    /**
     * 用户详情
     * @return mixed
     */
    public function userDetail(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field([
                'user_username',
                'user_image',
                'user_phone',
                'user_gender',
                'user_real_name',
                'user_shop_name',
                'user_time',
                'user_area_str',
                'user_bo_role',
                'user_bo_fy_balance',
                'user_bo_total_fy_balance',
                'user_bo_invite_other',
                'user_address',
                'user_status',
                'user_bo_district_role',
                'user_tz_code',
                'user_up_tz_code',
                'user_up_up_tz_code',
                'user_ty_code',
                'user_id',
                'user_is_recharge',
                'user_bo_total_balance',
                'user_bo_balance',
                'user_bo_first_balance',
                'user_bo_huo_balance',
                'user_bo_other_balance',
                'user_total_balance',
                'user_recharge_balance',
                'user_big_total_balance',
                'user_big_balance'
            ])
            ->find();

        // 上级
        if($user['user_bo_invite_other']){
            $user['superior'] = Db::table('up_u_user')->where('user_invite', $user['user_bo_invite_other'])->value('user_real_name');
        }else{
            $user['superior'] = '';
        }

        // 代理等级
        if($user['user_bo_district_role'] == 1){
            $district_role = '普通用户';
            $user['district_role'] = $district_role;
        }else{
            $district_role = '';
            if(strpos($user['user_bo_district_role'], ',2,') !== false) $district_role .= '县级运营商';
            if(strpos($user['user_bo_district_role'], ',3,') !== false) $district_role .= '，市级分公司';
            if(strpos($user['user_bo_district_role'], ',4,') !== false) $district_role .= '，省级子公司';
            $user['district_role'] = trim($district_role, '，');
        }

        // 团员、团队长编号、团员数量
        if($user['user_bo_role'] == 3){
            $tyCode = $user['user_up_tz_code'] . '_' . $user['user_ty_code'];
            $tzCode = '/';
            $tyNumber = 0;
        }elseif($user['user_bo_role'] == 4){
            $tzCode = $user['user_tz_code'];
            if(in_array($user['user_tz_code'], config('already_use'))){
                $tyCode = '/';
            }else{
                $tyCode = $user['user_up_tz_code'] . '_' . $user['user_ty_code'];
                $tzCode .= $user['user_up_tz_code'] == -1 ? '' : '_' . $user['user_up_tz_code'];
                $tzCode .= $user['user_up_up_tz_code'] == -1 ? '' : '_' . $user['user_up_up_tz_code'];
            }
            $tyNumber = Db::table('up_u_user')
                ->where('user_up_tz_code', $user['user_tz_code'])
//                ->where('user_bo_role', 3)
                ->count('user_id');
        }else{
            $tyCode = '/';
            $tzCode = '/';
            $tyNumber = 0;
        }
        $user['tyCode'] = $tyCode;
        $user['tzCode'] = $tzCode;
        $user['tyNumber'] = $tyNumber;


        return $this->fetch('', ['user' => $user]);
    }
    
    /**
     * 编辑用户
     * @return mixed|\think\response\Json
     */
    public function userEdit(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_username, user_image, user_phone, user_gender, user_real_name, user_shop_name, 
            user_bo_role, user_address, user_sheng, user_shi, user_qu, user_bank_username, 
            user_bank_name, user_bankcard_code, user_invite, user_bo_invite_other, user_bo_district_role')
            ->find();
        if(Request::instance()->isPost()){
            $user_image = input('user_image');
            $user_phone = input('user_phone');
            $user_password = input('user_password');
            $user_username = input('user_username');
            $user_gender = input('user_gender');
            $user_shop_name = input('user_shop_name');
//            $user_bo_role = input('user_bo_role');
            $user_bo_district_role = input('user_bo_district_role/a');
            if($user_bo_district_role){
                $user_bo_district_role = implode(',', $user_bo_district_role);
            }else{
                $user_bo_district_role = '1';
            }
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_address = input('user_address');
            $user_bank_username = input('user_bank_username');
            $user_bank_name = input('user_bank_name');
            $user_bankcard_code = input('user_bankcard_code');
            $user_real_name = input('user_real_name');
            $sheng_name = Db::table('up_area')->where('district_id', $user_sheng)->value('district');
            $shi_name = Db::table('up_area')->where('district_id', $user_shi)->value('district');
            $qu_name = Db::table('up_area')->where('district_id', $user_qu)->value('district');

            $exist = Db::table('up_u_user')
                ->where(['user_phone' => $user_phone, 'user_status' => 1, 'user_id' => ['NEQ', $user_id]])
                ->find();
            if($exist) return json(['code' => 100, 'msg' => '已有相同手机号']);

            // 是否有薄脸皮上级
            if($user_bo_district_role != '1'){
                if($user['user_invite'] != 'djl9988'){
                    if(!$user['user_bo_invite_other']){
                        return json(['code' => 100, 'msg' => '设置脖脸皮等级之前，请先绑定脖脸皮的上下级关系']);
                    }
                }
            }

            // 我的上级
            $upUser = Db::table('up_u_user')
                ->where('user_invite', $user['user_bo_invite_other'])
                ->field([
                    'user_id',
                    'user_bo_role',
                    'user_invite',
                    'user_tz_code',
                    'user_up_tz_code',
                    'user_up_up_tz_code'
                ])
                ->find();

            // 如果不是普通用户，则需要判断我的上级是否也是团员，
            // 如果我的上级也是团员，则需要判断上级推广了几个非普通用户，达到2个，则需要将上级升级成团队长
            $can = 0;  // 上级是否要升级成团长  0 不升级  1 升级
            if($user_bo_district_role != '1'){ // 如果不是普通用户
                if($upUser['user_bo_role'] != 4){
                    $number = Db::table('up_u_user')
                        ->where([
                            'user_bo_invite_other' => $upUser['user_invite'],
                            'user_bo_role' => ['>', 2],
                            'user_id' => ['<>', $user_id]
                        ])
                        ->count();
                    if($number == 1){
                        $can = 1; // 可以升级成团长
                    }
                }

            }
        
            $update = [
                'user_phone' => $user_phone,
                'user_username' => $user_username,
                'user_real_name' => $user_real_name,
                'user_gender' => $user_gender,
                'user_shop_name' => $user_shop_name,
//                'user_bo_role' => $user_bo_role,
                'user_sheng' => $user_sheng,
                'user_shi' => $user_shi,
                'user_qu' => $user_qu,
                'user_area_str' => $sheng_name . $shi_name . $qu_name,
                'user_address' => $user_address,
                'user_bank_username' => $user_bank_username,
                'user_bank_name' => $user_bank_name,
                'user_bankcard_code' => $user_bankcard_code,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
        
            if(!empty($user_image)) $update['user_image'] = $user_image;
            if(!empty($user_password)){
                $update['user_password'] = md5($user_password);
                $update['user_password_see'] = $user_password;
            }

            if($user_bo_district_role != '1'){
                $user_bo_district_role = ',' . $user_bo_district_role . ',';
            }
            $update['user_bo_district_role'] = $user_bo_district_role;

            // 如果我原来不是团长，现在成了代理，那需要改变我的身份，确定团队长编号等字段
            if($user['user_bo_role'] != 4 && $user_bo_district_role != '1'){
                $update['user_bo_role'] = 4; // 脖脸皮系统身份
                // 第一个未被使用的编号
                $code = $this->getFirstNoUseTzCode();
                $update['user_tz_code'] = $code['code']; // 团队长编号
//                $update['user_ty_code'] = 0;
                $_ty = $this->getTyCode($upUser['user_up_tz_code']);
                $update['user_ty_code'] = $_ty['user_ty_code'] + 1; // 团员编号
                if($user['user_bo_role'] != 3){ // 普通用户直接升团长
                    if($upUser['user_bo_role'] == 3){ // 如果上级是团员
                        $update['user_up_tz_code'] = $upUser['user_up_tz_code'];
                        $update['user_up_up_tz_code'] = $upUser['user_up_up_tz_code'];
                    }else{
                        $update['user_up_tz_code'] = $upUser['user_tz_code'];
                        $update['user_up_up_tz_code'] = $upUser['user_up_tz_code'];
                    }
                }
            }

            Db::startTrans();
            try{
                // 更新用户信息
                Db::table('up_u_user')->where('user_id', $user_id)->update($update);

                // 升级上级为团队长
                if($can == 1){
                    // 第一个未被使用的编号
                    $upCode = $this->getFirstNoUseTzCode();
                    $upTzCode = $upCode['code']; // 团队长编号
                    $upUserUpdate = [
                        'user_id' => $upUser['user_id'],
                        'user_bo_role' => 4,
                        'user_tz_code' => $upTzCode,
                        'user_ty_code' => 0,
                        'user_update_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_u_user')->update($upUserUpdate);
                }

                Db::commit();
                return json(['code' => 200, 'msg' => '编辑成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
    
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $city = Db::table('up_area')->where('pid', $user['user_sheng'])->field('district_id, district')->select();
        $qu = Db::table('up_area')->where('pid', $user['user_shi'])->field('district_id, district')->select();
        $user['user_bo_district_role'] = trim($user['user_bo_district_role'], ',');
        $this->assign([
            'user' => $user,
            'user_id' => $user_id,
            'province' => $province,
            'city' => $city,
            'qu' => $qu,
        ]);
        return $this->fetch('');
    }

    /**
     * 入系统
     * @return mixed|\think\response\Json
     */
    public function inSystem(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $first_balance = input('first_balance') ?: 0; // 首期款
            $inWay = input('inWay'); // 1 实际打款   2 添加身份
            $remark = input('remark');

            // 先判断有没有上级，再更新本人和上级系统身份，再查出新的身份，再充值

            if(!$first_balance){
                return json(['code' => 200, 'msg' => 'success']);
            }else{
                $user = Db::table('up_u_user')
                    ->where('user_id', $user_id)
                    ->field([
                        'user_invite',
                        'user_bo_invite_other',
                        'user_bo_role',
                        'user_recharge_price',
                        'user_bo_balance',
                        'user_real_name'
                    ])
                    ->find();

                if($user['user_invite'] != 'djl9988'){
                    if(!$user['user_bo_invite_other']){
                        return json(['code' => 100, 'msg' => '设置脖脸皮等级之前，请先绑定脖脸皮的上下级关系']);
                    }
                }

                $upUser = Db::table('up_u_user')
                    ->where('user_invite', $user['user_bo_invite_other'])
                    ->field([
                        'user_id',
                        'user_bo_role',
                        'user_tz_code',
                        'user_up_tz_code',
                        'user_up_up_tz_code',
                        'user_bo_fy_balance',
                        'user_teamer_status',
                        'user_invite',
                        'user_real_name'
                    ])
                    ->find();
                if($upUser['user_bo_role'] <= 2){
                    return json(['code' => 100, 'msg' => '上级权限不足']);
                }

                if($user['user_recharge_price'] != 0){
                    return json(['code' => 100, 'msg' => '该用户已充值过首批款，请不要重复充值']);
                }

                Db::startTrans();
                try{
                    //*********************************   变更我的身份  start  ********************//
                    if($first_balance == 19800){
                        $boRole = 3; // 团员
                    }else{
                        $boRole = 4; // 团长
                    }

                    if($upUser['user_bo_role'] == 3){ // 如果上级是团员
                        $upTz = $upUser['user_up_tz_code'];
                        $upUpTz = $upUser['user_up_up_tz_code'];
                    }else{
                        $upTz = $upUser['user_tz_code'];
                        $upUpTz = $upUser['user_up_tz_code'];
                    }
                    if($boRole == 3){ // 团员
                        $tzCode = -1; // 团队长编号
                    }else{ // 团长
                        // 第一个未被使用的编号
                        $code = $this->getFirstNoUseTzCode();
                        $tzCode = $code['code']; // 团队长编号
                    }
                    $_ty = $this->getTyCode($upTz);
                    $tyCode = $_ty['user_ty_code'] + 1; // 团员编号

                    $updateUser = [
                        'user_id' => $user_id,
                        'user_bo_role' => $boRole,
                        'user_tz_code' => $tzCode,
                        'user_ty_code' => $tyCode,
                        'user_up_tz_code' => $upTz,
                        'user_up_up_tz_code' => $upUpTz,
                        'user_recharge_price' => $first_balance,
                        'user_is_recharge' => $inWay,
                        'user_update_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_u_user')->update($updateUser);
                    //*********************************   变更我的身份  end  ********************//

                    //*********************************   变更上级身份  start  ********************//
                    // 如果上级不是团长，并且推广了两个团员，则可以升级成团长
                    $lowerCount = $this->getLowerNumber($upUser['user_invite']);
                    if($upUser['user_bo_role'] != 4 && $lowerCount == 2){
                        // 第一个未被使用的编号
                        $upCode = $this->getFirstNoUseTzCode();
                        $upTzCode = $upCode['code']; // 上级团队长编号

                        $upUserUpdate = [
                            'user_id' => $upUser['user_id'],
                            'user_bo_role' => 4,
                            'user_tz_code' => $upTzCode,
                            'user_update_time' => date('Y-m-d H:i:s')
                        ];
                        Db::table('up_u_user')->update($upUserUpdate);
                    }
                    //*********************************   变更上级身份  end  ********************//

                    if($inWay == 1){
                        //*********************************   首批款充值   start ********************//
                        // 1.用户积分
                        if($remark){
                            $descFirst = '首批款-' . $remark;
                        }else{
                            $descFirst = '首批款';
                        }
                        $this->insertBoInte($user_id, 1, $descFirst, $first_balance, $user['user_bo_balance'], 0);

                        Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->inc('user_bo_total_balance', $first_balance)
                            ->inc('user_bo_balance', $first_balance)
                            ->inc('user_bo_first_balance', $first_balance)
                            ->update();

                        //*********************************   首批款充值   end ********************//

                        //*********************************   首批款分佣   start ********************//
                        // 2.直开分佣
//                            $firstUpRatio = $this->getBoUserSystemFirstRatio(1, $zk, 0, $qd); // 提点比例
                        $firstUpRatio = config('default_first_up_ratio'); // 提点比例
                        $firstUpFy = $first_balance * $firstUpRatio / 100; // 分佣金额

                        $userFirst = Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->field([
                                'user_up_tz_code',
                                'user_up_up_tz_code',
                                'user_real_name'
                            ])
                            ->find();

                        // 直开&团长信息
                        $upFyUser = $this->getFirstFyUser(1, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($upFyUser);
                        if($upFyUser['up_role'] == 4){
                            $firstFyFrom = 1;
                        }else{
                            $firstFyFrom = 0;
                        }
                        $firstUpDesc = $user['user_real_name'] . '首批款-佣金';
                        $this->insertBoFy($upFyUser['user_id'], $user_id, $upFyUser['should_user_id'], $upFyUser['freeze_user_id'], 1, $firstUpDesc, 1, $firstUpFy, $upUser['user_bo_fy_balance'], 0, $upFyUser['hf'], $firstFyFrom, $upFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $upFyUser['user_id'])
                            ->inc('user_bo_fy_balance', $firstUpFy)
                            ->inc('user_bo_total_fy_balance', $firstUpFy)
                            ->update();


                        // 3.团长分佣
                        $tzFyUser = $this->getFirstFyUser(2, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($tzFyUser);die;
                        if($tzFyUser['should_user_id'] != 0){
//                                $firstTzRatio = $this->getBoUserSystemFirstRatio(2, 0, $tz, $qd); // 提点比例
                            $firstTzRatio = config('default_first_tz_ratio'); // 提点比例
                            $firstTzFy = $first_balance * $firstTzRatio / 100; // 分佣金额
                            $firstTzDesc = $userFirst['user_real_name'] . '首批款-佣金';

                            $this->insertBoFy($tzFyUser['user_id'], $user_id, $tzFyUser['should_user_id'], $tzFyUser['freeze_user_id'], 1, $firstTzDesc, 1, $firstTzFy, $tzFyUser['bo_balance'], 0, $tzFyUser['hf'], 1, $tzFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $tzFyUser['user_id'])
                                ->inc('user_bo_fy_balance', $firstTzFy)
                                ->inc('user_bo_total_fy_balance', $firstTzFy)
                                ->update();
                        }
                        //*********************************   首批款分佣   end ********************//
                    }

                    Db::commit();
                    return json(['code' => 200, 'msg' => '操作成功']);
                }catch (\Exception $e){
                    Db::rollback();
                    return json(['code' => 100, 'msg' => $e->getMessage()]);
                }

            }
        }
        $showUser = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_real_name, user_phone, user_area_str, user_bo_invite_other, user_bo_balance')
            ->find();
        if($showUser['user_bo_invite_other']){
            $showUser['superior'] = Db::table('up_u_user')->where('user_invite', $showUser['user_bo_invite_other'])->value('user_real_name');
        }else{
            $showUser['superior'] = '';
        }
        $xieUser = Db::table('up_u_user')
            ->where([
                'user_bo_role' => ['BETWEEN', [3, 4]],
                'user_status' => 1,
                'user_teamer_status' => 1
            ])
            ->field('user_id, user_real_name, user_phone')
            ->select();
        return $this->fetch('', ['user_id' => $user_id, 'user' => $showUser, 'xieUser' => $xieUser]);
    }

    /**
     * 充值-----弃用
     * @return mixed|\think\response\Json
     */
//    public function userRecharge(){
//        $user_id = input('user_id');
//        if(Request::instance()->isPost()){
//            $first_balance = input('first_balance') ?: 0; // 首期款
//            $qd = input('qd'); // 渠道    1 线上    2 线下
//            $zk = input('zk'); // 直开协助  1 有   2 无
//            $tz = input('tz'); // 团长协助  1 有   2 无
//            $inSystem = input('inSystem'); // 1 实际打款入系统  2 添加身份入系统
//            $xie_user_id = input('xie_user_id'); // 帮忙开发的用户，拿走直开奖励的50%
//            $huo_balance = input('huo_balance'); // 货款
//            $integral_remark_huo = input('integral_remark_huo'); // 货款备注
////            $is_fy = input('is_fy'); // 补货款是否进行分佣    1 是   2 否
//            $ms_balance = input('ms_balance'); // 秒杀款
//            $ms_remark = input('ms_remark'); // 秒杀款备注
//            $th_balance = input('th_balance'); // 特惠商品款
//            $th_remark = input('th_remark'); // 特惠商品款备注
//            $other_balance = input('other_balance'); // 其它款项
//            $other_remark = input('other_remark'); // 其它款项备注
//
//            // 先判断有没有上级，再更新本人和上级系统身份，再查出新的身份，再充值
//
//            if(!$first_balance && !$huo_balance && !$ms_balance && !$th_balance && !$other_balance){
//                return json(['code' => 200, 'msg' => 'success']);
//            }else{
//                $user = Db::table('up_u_user')
//                    ->where('user_id', $user_id)
//                    ->field('user_invite, user_bo_invite_other, user_bo_role, user_recharge_price')
//                    ->find();
//
//                if($user['user_invite'] != 'djl9988'){
//                    if(!$user['user_bo_invite_other']){
//                        return json(['code' => 100, 'msg' => '设置脖脸皮等级之前，请先绑定脖脸皮的上下级关系']);
//                    }
//                }
//
//                $upUser = Db::table('up_u_user')
//                    ->where('user_invite', $user['user_bo_invite_other'])
//                    ->field([
//                        'user_id',
//                        'user_bo_role',
//                        'user_tz_code',
//                        'user_up_tz_code',
//                        'user_up_up_tz_code',
//                        'user_bo_fy_balance',
//                        'user_teamer_status',
//                        'user_invite'
//                    ])
//                    ->find();
//                if($upUser['user_bo_role'] <= 2){
//                    return json(['code' => 100, 'msg' => '上级权限不足']);
//                }
//
//                Db::startTrans();
//                try{
//                    // 有首批款的时候，先变更我的身份和上级身份，团员OR团队长，
//                    if($first_balance){
//                        //*********************************   变更我的身份  start  ********************//
//                        if($user['user_recharge_price'] != 0){
//                            return json(['code' => 100, 'msg' => '该用户已充值过首批款，请不要重复充值']);
//                        }
//                        if($first_balance == 19800){
//                            $boRole = 3; // 团员
//                        }else{
//                            $boRole = 4; // 团长
//                        }
//
//                        if($upUser['user_bo_role'] == 3){ // 如果上级是团员
//                            $upTz = $upUser['user_up_tz_code'];
//                            $upUpTz = $upUser['user_up_up_tz_code'];
//                        }else{
//                            $upTz = $upUser['user_tz_code'];
//                            $upUpTz = $upUser['user_up_tz_code'];
//                        }
//                        if($boRole == 3){ // 团员
//                            $tzCode = -1; // 团队长编号
////                            $_ty = $this->getTyCode($upTz);
////                            $tyCode = $_ty['user_ty_code'] + 1; // 团员编号
//
//                        }else{ // 团长
//                            // 第一个未被使用的编号
//                            $code = $this->getFirstNoUseTzCode();
//                            $tzCode = $code['code']; // 团队长编号
////                            $_ty = $this->getTyCode($upTz);
////                            $tyCode = $_ty['user_ty_code'] + 1; // 团员编号
//                        }
//                        $_ty = $this->getTyCode($upTz);
//                        $tyCode = $_ty['user_ty_code'] + 1; // 团员编号
//
//                        $updateUser = [
//                            'user_id' => $user_id,
//                            'user_bo_role' => $boRole,
//                            'user_tz_code' => $tzCode,
//                            'user_ty_code' => $tyCode,
//                            'user_up_tz_code' => $upTz,
//                            'user_up_up_tz_code' => $upUpTz,
//                            'user_recharge_price' => $first_balance,
//                            'user_is_recharge' => $inSystem,
//                            'user_update_time' => date('Y-m-d H:i:s')
//                        ];
//                        Db::table('up_u_user')->update($updateUser);
//
//                        //******************************  变更上级身份
//                        // 如果上级不是团长，并且推广了两个团员，则可以升级成团长
//                        $lowerCount = $this->getLowerNumber($upUser['user_invite']);
//                        if($upUser['user_bo_role'] != 4 && $lowerCount == 2){
//                            // 第一个未被使用的编号
//                            $upCode = $this->getFirstNoUseTzCode();
//                            $upTzCode = $upCode['code']; // 上级团队长编号
//
//                            $upUserUpdate = [
//                                'user_id' => $upUser['user_id'],
//                                'user_bo_role' => 4,
//                                'user_tz_code' => $upTzCode,
////                                'user_ty_code' => 0,
//                                'user_update_time' => date('Y-m-d H:i:s')
//                            ];
//                            Db::table('up_u_user')->update($upUserUpdate);
//                        }
//                        //*********************************   变更我的身份  end  ********************//
//
//                        //*********************************   首批款充值   start ********************//
//                        if($inSystem == 1){
//                            // 1.用户积分
//                            $userFirst = Db::table('up_u_user')->where('user_id', $user_id)
//                                ->field([
////                            'user_bo_role',
////                            'user_bo_total_balance',
//                                    'user_bo_balance',
////                            'user_bo_first_balance',
//                                    'user_bo_invite_other',
//                                    'user_real_name',
//                                    'user_up_tz_code',
//                                    'user_up_up_tz_code'
//                                ])
//                                ->find();
//
//                            insertBoInte($user_id, 0, 1, '首批款充值', $first_balance, $userFirst['user_bo_balance'], 0, 4, 1);
//
//                            Db::table('up_u_user')
//                                ->where('user_id', $user_id)
//                                ->inc('user_bo_total_balance', $first_balance)
//                                ->inc('user_bo_balance', $first_balance)
//                                ->inc('user_bo_first_balance', $first_balance)
//                                ->update();
//
//                            //*********************************   首批款充值   end ********************//
//
//                            //*********************************   首批款分佣   start ********************//
//                            // 2.直开分佣
//                            $firstUpRatio = $this->getBoUserSystemFirstRatio(1, $zk, 0, $qd); // 提点比例
//                            $firstUpFy = $first_balance * $firstUpRatio / 100; // 分佣金额
//
//                            // 如果有帮助开发的人，这个直开奖励需要分一半出去
//                            if($xie_user_id){
//                                $firstUpFy = round($firstUpFy / 2, 2);
//                                $help = Db::table('up_u_user')
//                                    ->where('user_id', $xie_user_id)
//                                    ->field('user_bo_fy_balance')
//                                    ->find();
//
//                                $firstUpDesc = $userFirst['user_real_name'] . '首批款帮助开发-佣金';
//                                insertBoInte($xie_user_id, $user_id, 3, $firstUpDesc, $firstUpFy, $help['user_bo_fy_balance'], 0, 4, 2, 2, $xie_user_id);
//
//                                Db::table('up_u_user')
//                                    ->where('user_id', $xie_user_id)
//                                    ->inc('user_bo_fy_balance', $firstUpFy)
//                                    ->inc('user_bo_total_fy_balance', $firstUpFy)
//                                    ->update();
//                            }
//
//                            // 直开&团长信息
//                            $upFyUser = $this->getFirstFyUser(1, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
////                        print_r($upFyUser);
//                            if($upFyUser['up_role'] == 4){
//                                $firstFyFrom = 1;
//                            }else{
//                                $firstFyFrom = 0;
//                            }
//                            $firstUpDesc = $userFirst['user_real_name'] . '首批款-佣金';
//                            insertBoInte($upFyUser['user_id'], $user_id, 3, $firstUpDesc, $firstUpFy, $upFyUser['bo_balance'], 0, 4, 2, $upFyUser['hf'], $upFyUser['should_user_id'], $firstFyFrom, $upFyUser['freeze_user_id']);
//
//                            Db::table('up_u_user')
//                                ->where('user_id', $upFyUser['user_id'])
//                                ->inc('user_bo_fy_balance', $firstUpFy)
//                                ->inc('user_bo_total_fy_balance', $firstUpFy)
//                                ->update();
//
//
//                            // 3.团长分佣
//                            $tzFyUser = $this->getFirstFyUser(2, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
////                        print_r($tzFyUser);die;
//                            if($tzFyUser['should_user_id'] != 0){
//                                $firstTzRatio = $this->getBoUserSystemFirstRatio(2, 0, $tz, $qd); // 提点比例
//                                $firstTzFy = $first_balance * $firstTzRatio / 100; // 分佣金额
//                                $firstTzDesc = $userFirst['user_real_name'] . '首批款-佣金';
//
//                                insertBoInte($tzFyUser['user_id'], $user_id, 3, $firstTzDesc, $firstTzFy, $tzFyUser['bo_balance'], 0, 4, 2, $tzFyUser['hf'], $tzFyUser['should_user_id'], 1, $tzFyUser['freeze_user_id']);
//
//                                Db::table('up_u_user')
//                                    ->where('user_id', $tzFyUser['user_id'])
//                                    ->inc('user_bo_fy_balance', $firstTzFy)
//                                    ->inc('user_bo_total_fy_balance', $firstTzFy)
//                                    ->update();
//                            }
//                        }
//
//                        //*********************************   首批款分佣   end ********************//
//                    }
//
//                    if($huo_balance){
//                        //*************************  补货款充值   start ****************************//
//                        // 1.用户补货款
//                        $userHuo = Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->field([
//                                'user_bo_role',
////                            'user_bo_total_balance',
//                                'user_bo_balance',
////                            'user_bo_first_balance',
//                                'user_bo_invite_other',
//                                'user_real_name',
//                                'user_up_tz_code',
//                                'user_up_up_tz_code',
//                                'user_sheng',
//                                'user_shi',
//                                'user_qu'
//                            ])
//                            ->find();
//
//                        // 用户积分明细
//                        if($integral_remark_huo){
//                            $descHuo = '补货款-' . $integral_remark_huo;
//                        }else{
//                            $descHuo = '补货款';
//                        }
//                        insertBoInte($user_id, 0, 1, $descHuo, $huo_balance, $userHuo['user_bo_balance'], 0, 4, 1);
//
//                        // 用户积分
//                        Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->inc('user_bo_total_balance', $huo_balance)
//                            ->inc('user_bo_balance', $huo_balance)
//                            ->inc('user_bo_huo_balance', $huo_balance)
//                            ->update();
//                        //*************************  补货款充值   end ****************************//
//
//                        // 补货款的分佣已经迁移到订单确认收货，此处暂时作废----2023.08.07
////                        if($is_fy == 1 && $huo_balance != 0){
//                        if(0){
//                            //*************************  团长分佣   start ****************************//
//                            // 2.本团/上级分佣
////                            $upHuoFyUser = $this->getBoUserSystemHuo(1, $userHuo['user_bo_role'], $userHuo['user_up_tz_code'], $userHuo['user_up_up_tz_code']);
////                            if($upHuoFyUser['should_user_id'] != 0){
////                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
////                                if($huo_balance > 0){
////                                    $descFyHuo1 = $userHuo['user_real_name'] . '补货款-佣金';
////                                    $binteTypeHuo1 = 3;
////                                    $huoBalanceFy1 = $huoTzFy1;
////                                }else{
////                                    $descFyHuo1 = $userHuo['user_real_name'] . '补货款-佣金回退';
////                                    $binteTypeHuo1 = 4;
////                                    $huoBalanceFy1 = 0 - $huoTzFy1;
////                                }
////
////                                insertBoInte($upHuoFyUser['tz_user_id'], $user_id, $binteTypeHuo1, $descFyHuo1, $huoBalanceFy1, $upHuoFyUser['bo_balance'], 0, 4, 2, $upHuoFyUser['should_user_id'], 1);
////
////                                Db::table('up_u_user')
////                                    ->where('user_id', $upHuoFyUser['tz_user_id'])
////                                    ->inc('user_bo_fy_balance', $huoTzFy1)
////                                    ->inc('user_bo_total_fy_balance', $huoTzFy1)
////                                    ->update();
////                            }
//
//                            // 3.上级/上上级团队长分佣
////                            $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $userHuo['user_bo_role'], $userHuo['user_up_tz_code'], $userHuo['user_up_up_tz_code']);
////                            if($upUpHuoFyUser['should_user_id'] != 0){
////                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
////                                if($huo_balance > 0){
////                                    $descFyHuo2 = $userHuo['user_real_name'] . '补货款-佣金';
////                                    $binteTypeHuo2 = 3;
////                                    $huoBalanceFy2 = $huoTzFy2;
////                                }else{
////                                    $descFyHuo2 = $userHuo['user_real_name'] . '补货款-佣金回退';
////                                    $binteTypeHuo2 = 4;
////                                    $huoBalanceFy2 = 0 - $huoTzFy2;
////                                }
////
////                                insertBoInte($upUpHuoFyUser['tz_user_id'], $user_id, $binteTypeHuo2, $descFyHuo2, $huoBalanceFy2, $upUpHuoFyUser['bo_balance'], 0, 4, 2, $upUpHuoFyUser['should_user_id'], 1);
////
////                                Db::table('up_u_user')
////                                    ->where('user_id', $upUpHuoFyUser['tz_user_id'])
////                                    ->inc('user_bo_fy_balance', $huoTzFy2)
////                                    ->inc('user_bo_total_fy_balance', $huoTzFy2)
////                                    ->update();
////                            }
//                            //*************************  团长分佣   end ****************************//
//
//                            //*************************  代理分佣   start ****************************//
//                            // 4.县代管理费
////                            $quFyUser = $this->getDaiLiFy(3, $userHuo['user_qu']);
////                            if($quFyUser['should_user_id'] != 0){
////                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
////                                if($huo_balance > 0){
////                                    $descFyHuo3_dl = $userHuo['user_real_name'] . '补货款-县管理费';
////                                    $binteTypeHuo3_dl = 3;
////                                    $huoBalanceFy3_dl = $huoDlFy3;
////                                }else{
////                                    $descFyHuo3_dl = $userHuo['user_real_name'] . '补货款-县管理费回退';
////                                    $binteTypeHuo3_dl = 4;
////                                    $huoBalanceFy3_dl = 0 - $huoDlFy3;
////                                }
////
////                                insertBoInte($quFyUser['fy_user_id'], $user_id, $binteTypeHuo3_dl, $descFyHuo3_dl, $huoBalanceFy3_dl, $quFyUser['bo_balance'], 0, 4, 2, $quFyUser['should_user_id'], 2);
////
////                                Db::table('up_u_user')
////                                    ->where('user_id', $quFyUser['fy_user_id'])
////                                    ->inc('user_bo_fy_balance', $huoDlFy3)
////                                    ->inc('user_bo_total_fy_balance', $huoDlFy3)
////                                    ->update();
////                            }
////
//                              // 5.市代管理费
////                            $shiFyUser = $this->getDaiLiFy(2, $userHuo['user_shi']);
////                            if($shiFyUser['should_user_id'] != 0){
////                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
////                                if($huo_balance > 0){
////                                    $descFyHuo2_dl = $userHuo['user_real_name'] . '补货款-市管理费';
////                                    $binteTypeHuo2_dl = 3;
////                                    $huoBalanceFy2_dl = $huoDlFy2;
////                                }else{
////                                    $descFyHuo2_dl = $userHuo['user_real_name'] . '补货款-市管理费回退';
////                                    $binteTypeHuo2_dl = 4;
////                                    $huoBalanceFy2_dl = 0 - $huoDlFy2;
////                                }
////
////                                insertBoInte($shiFyUser['fy_user_id'], $user_id, $binteTypeHuo2_dl, $descFyHuo2_dl, $huoBalanceFy2_dl, $shiFyUser['bo_balance'], 0, 4, 2, $shiFyUser['should_user_id'], 3);
////
////                                Db::table('up_u_user')
////                                    ->where('user_id', $shiFyUser['fy_user_id'])
////                                    ->inc('user_bo_fy_balance', $huoDlFy2)
////                                    ->inc('user_bo_total_fy_balance', $huoDlFy2)
////                                    ->update();
////                            }
//
//                            // 6.省代管理费
////                            $shengFyUser = $this->getDaiLiFy(1, $userHuo['user_sheng']);
////                            if($shengFyUser['should_user_id'] != 0){
////                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
////                                if($huo_balance > 0){
////                                    $descFyHuo1_dl = $userHuo['user_real_name'] . '补货款-省管理费';
////                                    $binteTypeHuo1_dl = 3;
////                                    $huoBalanceFy1_dl = $huoDlFy1;
////                                }else{
////                                    $descFyHuo1_dl = $userHuo['user_real_name'] . '补货款-省管理费回退';
////                                    $binteTypeHuo1_dl = 4;
////                                    $huoBalanceFy1_dl = 0 - $huoDlFy1;
////                                }
////
////                                insertBoInte($shengFyUser['fy_user_id'], $user_id, $binteTypeHuo1_dl, $descFyHuo1_dl, $huoBalanceFy1_dl, $shengFyUser['bo_balance'], 0, 4, 2, $shengFyUser['should_user_id'], 4);
////
////                                Db::table('up_u_user')
////                                    ->where('user_id', $shengFyUser['fy_user_id'])
////                                    ->inc('user_bo_fy_balance', $huoDlFy1)
////                                    ->inc('user_bo_total_fy_balance', $huoDlFy1)
////                                    ->update();
////                            }
//                            //*************************  代理分佣   end ****************************//
//                        }
//                    }
//
//                    if($ms_balance){
//                        //******************  秒杀款项充值（不参与分佣）   start   **********************//
//                        $user_ms = Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->field('user_bo_miao_balance, user_bo_ky_balance_t, user_bo_total_balance_t')
//                            ->find();
//                        if($ms_remark){
//                            $desc_ms = '秒杀款项-' . $ms_remark;
//                        }else{
//                            $desc_ms = '秒杀款项';
//                        }
//                        // 用户积分明细
//                        insertBoOtherInte($user_id, 1, $desc_ms, $ms_balance, $user_ms['user_bo_ky_balance_t'], 0, 1);
//
//                        // 用户积分
//                        Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->inc('user_bo_miao_balance', $ms_balance)
//                            ->inc('user_bo_ky_balance_t', $ms_balance)
//                            ->inc('user_bo_total_balance_t', $ms_balance)
//                            ->update();
//                        //******************  秒杀款项充值（不参与分佣）   end   **********************//
//                    }
//
//                    if($th_balance){
//                        //******************  特惠商品款项充值（不参与分佣）   start   **********************//
//                        $user_th = Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->field('user_bo_t_balance, user_bo_ky_balance_t, user_bo_total_balance_t')
//                            ->find();
//                        if($th_remark){
//                            $desc_th = '特惠款项-' . $th_remark;
//                        }else{
//                            $desc_th = '特惠款项';
//                        }
//                        // 用户积分明细
//                        insertBoOtherInte($user_id, 1, $desc_th, $th_balance, $user_th['user_bo_ky_balance_t'], 0, 2);
//
//                        // 用户积分
//                        Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->inc('user_bo_t_balance', $th_balance)
//                            ->inc('user_bo_ky_balance_t', $th_balance)
//                            ->inc('user_bo_total_balance_t', $th_balance)
//                            ->update();
//                        //******************  特惠商品款项充值（不参与分佣）   end   **********************//
//                    }
//
//                    if($other_balance){
//                        //******************  其它款项充值（不参与分佣）   start   **********************//
//                        $user_other = Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->field('user_bo_other_balance, user_bo_ky_balance_t, user_bo_total_balance_t')
//                            ->find();
//
//                        // 用户积分明细
//                        if($other_remark){
//                            $desc_other = '其它款项-' . $other_remark;
//                        }else{
//                            $desc_other = '其它款项';
//                        }
//                        // 用户积分明细
//                        insertBoOtherInte($user_id, 1, $desc_other, $other_balance, $user_other['user_bo_ky_balance_t'], 0, 3);
//
//                        // 用户积分
//                        Db::table('up_u_user')
//                            ->where('user_id', $user_id)
//                            ->inc('user_bo_other_balance', $other_balance)
//                            ->inc('user_bo_ky_balance_t', $other_balance)
//                            ->inc('user_bo_total_balance_t', $other_balance)
//                            ->update();
//                        //******************  其它款项充值（不参与分佣）   end   **********************//
//                    }
//
//                    Db::commit();
//                    return json(['code' => 200, 'msg' => '充值成功']);
//                }catch(\Exception $e){
//                    Db::rollback();
//                    return json(['code' => 100, 'msg' => $e->getLine() . ':' . $e->getMessage()]);
//                }
//            }
//        }
//        $showUser = Db::table('up_u_user')
//            ->where('user_id', $user_id)
//            ->field('user_real_name, user_phone, user_area_str, user_bo_invite_other, user_bo_balance')
//            ->find();
//        if($showUser['user_bo_invite_other']){
//            $showUser['superior'] = Db::table('up_u_user')->where('user_invite', $showUser['user_bo_invite_other'])->value('user_real_name');
//        }else{
//            $showUser['superior'] = '';
//        }
//        return $this->fetch('', ['user_id' => $user_id, 'user' => $showUser]);
//    }
    
    /**
     * 冻结---作废
     * @return \think\response\Json
     */
    public function userFreeze(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 2);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 启用---作废
     * @return \think\response\Json
     */
    public function userUsing(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 1);
        if($res){
            return json(['code' => 200, 'msg' => '启用成功']);
        }else{
            return json(['code' => 100, 'msg' => '启用失败']);
        }
    }
    
    /**
     * 收货地址---作废
     * @return mixed|\think\response\Json
     */
    public function userAddress(){
        if(request()->isAjax ()){
            $where['addr_user_id'] = session('b_user_id');
            $where['addr_del'] = 1;
            $where['addr_from'] = 2;
        
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_user_address')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_user_address')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->field('addr_id, addr_user_name, addr_user_phone, u1.district sheng, u2.district shi, 
                u3.district qu, addr_address, addr_is_default, addr_time')
                ->where($where)
                ->order('addr_is_default asc, addr_time desc')
                ->page($Nowpage, $limits)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        if(isset($user_id) && $user_id != '') session('b_user_id', $user_id);
        return $this->fetch('');
    }

    /**
     *  团队长系统
     * @return mixed|\think\response\Json
     */
    public function userSystem(){
        if(Request::instance()->isAjax()){
            $tzCode = Db::table('up_u_user')->where('user_id', session('s_user_id'))->value('user_tz_code');
            if($tzCode){
                $keyword = input('keyword');
                $role = input('bo_role');

                if(session('s_user_id') == config('company_xn_user')){
                    $where['user_tz_code'] = ['IN', config('already_use')];
                }else{
                    $where['user_up_tz_code'] = $tzCode;
                }
                if($keyword) $where['user_real_name|user_phone'] = ['LIKE', '%' . $keyword . '%'];
                if($role) $where['user_bo_role'] = $role;
                $Nowpage = input('page') ? input('page') : 1;
                $limits = input("limit") ? input("limit") : 10;
                $count = Db::table('up_u_user')
                    ->where($where)
                    ->count();// 获取总条数
                $lists = Db::table('up_u_user')
                    ->field('user_id, user_real_name, user_phone, user_bo_role, user_tz_code, 
                    user_ty_code, user_up_tz_code, user_up_up_tz_code')
                    ->where($where)
                    ->page($Nowpage,$limits)
                    ->select();
            }else{
                $Nowpage = input('page') ? input('page') : 1;
                $limits = input("limit") ? input("limit") : 10;
                $count = 0;
                $lists = [];
            }
            if($lists){
                foreach ($lists as $k => $v){
                    $tyCode = '/';
                    $tzCode = '/';
                    $bo_role = '/';
                    if($v['user_bo_role'] == 3){
                        $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                        $bo_role = '团员';
                    }elseif($v['user_bo_role'] == 4){
                        $tzCode = $v['user_tz_code'];
                        if(!in_array($v['user_tz_code'], config('already_use'))){
                            $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                            $tzCode .= $v['user_up_tz_code'] == -1 ? '' : '_' . $v['user_up_tz_code'];
                        }
                        $tzCode .= $v['user_up_up_tz_code'] == -1 ? '' : '_' . $v['user_up_up_tz_code'];
                        $bo_role = '团队长';
                    }
                    $lists[$k]['tyCode'] = $tyCode;
                    $lists[$k]['tzCode'] = $tzCode;
                    $lists[$k]['bo_role'] = $bo_role;
                }

            }

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        if(isset($user_id) && $user_id != '') session('s_user_id', $user_id);
        return $this->fetch('');
    }
    
    /**
     * 下级列表
     * @return mixed|\think\response\Json
     */
    public function userLower(){
        if(Request::instance()->isAjax()){
            $user_invite = Db::table('up_u_user')->where('user_id', session('b_user_id'))->value('user_invite');
            if($user_invite){
                $where['user_bo_invite_other'] = $user_invite;
                $Nowpage = input('page') ? input('page') : 1;
                $limits = input("limit") ? input("limit") : 10;
                $count = Db::table('up_u_user')
                    ->where($where)
                    ->count();// 获取总条数
                $lists = Db::table('up_u_user')
                    ->field('user_id, user_real_name, user_phone')
                    ->where($where)
                    ->page($Nowpage,$limits)
                    ->select();
            }else{
                $Nowpage = input('page') ? input('page') : 1;
                $limits = input("limit") ? input("limit") : 10;
                $count = 0;
                $lists = [];
            }
        
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        if(isset($user_id) && $user_id != '') session('b_user_id', $user_id);
        return $this->fetch('');
    }
    
    /**
     * 选择下级
     * @return mixed|\think\response\Json
     */
    public function lowerAdd(){
        $user_invite = Db::table('up_u_user')->where('user_id', session('b_user_id'))->value('user_invite');
        if(Request::instance()->isPost()){
            $user_id = input('user_id');

            // 半年保护，如果半年内，上级和该用户购买礼包时的上级不一致，则不允许绑定
            // 如果选择的下级没有购买过礼包，则不做判断
            $alreadyBuy = Db::table('up_bo_orderg')
                ->where(['bog_user_id' => $user_id, 'bog_is_pay' => 2])
                ->order('bog_create_time asc')
                ->find();
            $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_giftbag_invite_other, user_giftbag_date')->find();
            if($alreadyBuy){
                $month = date('Y-m-d');
                $privateDays = Db::table('up_bo_fy_config')->where('bfc_id', 40)->value('bfc_content');
                if($privateDays != 0){
                    $halfYear = date('Y-m-d', strtotime("+{$privateDays} days", strtotime($alreadyBuy['bog_pay_time'])));
                    if($halfYear >= $month){ // 半年以内
                        if($user_invite != $user['user_giftbag_invite_other']){
                            $up_user = Db::table('up_u_user')->where('user_invite', $user['user_giftbag_invite_other'])->field('user_phone')->find();
                            return json(['code' => 100, 'msg' => "该下级处于半年保护时间内,不可配置其他上级,礼包上级是：{$up_user['user_phone']}"]);
                        }
                    }
                }
            }

            $update = [
                'user_bo_invite_other' => $user_invite
            ];

            if(!$user['user_giftbag_invite_other']){
                $update['user_giftbag_invite_other'] = 'djl9988';
            }
            if(!$user['user_giftbag_date']){
                $update['user_giftbag_date'] = date('Y-m-d');
            }

            $res = Db::table('up_u_user')->where('user_id', $user_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '选择成功']);
            }else{
                return json(['code' => 100, 'msg' => '选择失败']);
            }
        }
        $user_bo_invite_other = Db::table('up_u_user')->where('user_id', session('h_user_id'))->value('user_bo_invite_other');
        $where = [
            'user_status' => 1,
            'user_id' => [['NEQ', session('b_user_id')], ['NEQ', config('company_user')], 'AND'],
            'user_bo_invite_other' => ['EQ', '0']
        ];
        if($user_bo_invite_other){
            $where['user_invite'] = ['NEQ', $user_bo_invite_other];
        }
        $user = Db::table('up_u_user')
            ->where($where)
            ->field('user_id, user_real_name, user_phone, user_bo_role, user_giftbag_level')
            ->select();
        return $this->fetch('', ['user' => $user]);
    }
    
    /**
     * 删除下级
     * @return \think\response\Json
     */
    public function lowerDel(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_bo_invite_other', '0');
        if($res){
            return json(['code' => 200, 'msg' => '移除成功']);
        }else{
            return json(['code' => 100, 'msg' => '移除失败']);
        }
    }
    
    /**
     * 佣金充值
     * @return mixed|\think\response\Json
     */
    public function userYj(){
        $user_id = input('user_id');
        $showUser = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_real_name, user_phone, user_bo_fy_balance')
            ->find();
        if(Request::instance()->isPost()){
            $yj = input('yj');
            $way = input('way') ? input('way') : 1;
            $remark = input('remark');
            if($way == 1){
                $price = $yj;
                $desc = '系统添加佣金';
            }else{
                $price = 0 - $yj;
                $desc = '系统扣除佣金';
            }
            if($remark) $desc = $desc . '-' . $remark;
            Db::startTrans();
            try{
                // 佣金明细
                $this->insertBoFy($user_id, 0, $user_id, 0, $way, $desc, 1, $yj, $showUser['user_bo_fy_balance'], 0, 2, 0);

                // 用户佣金
                Db::table('up_u_user')
                    ->where('user_id', $user_id)
                    ->inc('user_bo_total_fy_balance', $price)
                    ->inc('user_bo_fy_balance', $price)
                    ->update();

                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('', ['user_id' => $user_id, 'user' => $showUser]);
    }

    /**
     * 积分充值
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userBalance(){
        $user_id = input('user_id');
        $showUser = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field([
                'user_real_name',
                'user_phone',
                'user_bo_invite_other',
                'user_recharge_balance',
                'user_bo_balance',
                'user_invite',
                'user_bo_role',
                'user_recharge_price',
                'user_bo_balance',
                'user_up_tz_code',
                'user_up_up_tz_code',
                'user_sheng',
                'user_shi',
                'user_qu'
            ])
            ->find();
        if(Request::instance()->isPost()){
            $balance = input('balance');
            $way = input('way'); // 1 增加   2 减少
            $remark = input('remark');
            $project = input('project');
            $isFy = input('isFy'); // 1 分佣   2 不分佣
            if($project == 2){
                $projectName = '补货款';
            }elseif ($project == 7){
                $projectName = '其它款';
            }else{
                $projectName = '特惠商品';
            }
            if($way == 1){
                $price = $balance;
                $desc = '系统增加_' . $projectName;
                $fyDesc = '增加';
            }else{
                $price = 0 - $balance;
                $desc = '系统扣除_' . $projectName;
                $fyDesc = '扣除';
            }
            if($remark) $desc = $desc . '_' . $remark;

            Db::startTrans();
            try{
                // 积分明细
                if($project == 7){ // 其它款
                    $this->insertBoInte($user_id, $way, $desc, $balance, $showUser['user_bo_balance'], 0);

                    Db::table('up_u_user')
                        ->where('user_id', $user_id)
                        ->inc('user_bo_total_balance', $price)
                        ->inc('user_bo_balance', $price)
                        ->inc('user_bo_other_balance', $price)
                        ->update();
                }elseif($project == 4){ // 特惠商品
                    // 用户积分明细
                    $this->insertThInte($user_id, $way, $desc, $balance, $showUser['user_recharge_balance'], 0);

                    Db::table('up_u_user')
                        ->where('user_id', $user_id)
                        ->inc('user_total_balance', $price)
                        ->inc('user_recharge_balance', $price)
                        ->update();
                }else{ // 补货款
                    // ********************************  用户补货款  start  ***************************//
                    $this->insertBoInte($user_id, $way, $desc, $balance, $showUser['user_bo_balance'], 0);

                    Db::table('up_u_user')
                        ->where('user_id', $user_id)
                        ->inc('user_bo_total_balance', $price)
                        ->inc('user_bo_balance', $price)
                        ->inc('user_bo_huo_balance', $price)
                        ->update();
                    // ********************************  用户补货款  end    ***************************//

                    if($isFy == 1){
                        //*************************  团长分佣   start ****************************//
                        // 2.本团/上级分佣
                        $upHuoFyUser = $this->getBoUserSystemHuo(1, $showUser['user_bo_role'], $showUser['user_up_tz_code'], $showUser['user_up_up_tz_code']);
                        if($upHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
                            $huoTzFy1 = $balance * config('default_huo_tz_ratio') / 100; // 分佣金额
                            $_huoTzFy1 = $price * config('default_huo_tz_ratio') / 100; // 分佣金额
                            $descFyHuo1 = $showUser['user_real_name'] . '补货款-佣金' . $fyDesc;

                            $this->insertBoFy($upHuoFyUser['tz_user_id'], $user_id, $upHuoFyUser['should_user_id'], $upHuoFyUser['freeze_user_id'], $way, $descFyHuo1, 1, $huoTzFy1, $upHuoFyUser['bo_balance'], 0, $upHuoFyUser['hf'], 1, $upHuoFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $upHuoFyUser['tz_user_id'])
                                ->inc('user_bo_fy_balance', $_huoTzFy1)
                                ->inc('user_bo_total_fy_balance', $_huoTzFy1)
                                ->update();

                        }

                        // 3.上级/上上级团队长分佣
                        $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $showUser['user_bo_role'], $showUser['user_up_tz_code'], $showUser['user_up_up_tz_code']);
                        if($upUpHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
                            $huoTzFy2 = $balance * config('default_huo_tz_ratio') / 100; // 分佣金额
                            $_huoTzFy2 = $price * config('default_huo_tz_ratio') / 100; // 分佣金额
                            $descFyHuo2 = $showUser['user_real_name'] . '补货款-佣金' . $fyDesc;

                            $this->insertBoFy($upUpHuoFyUser['tz_user_id'], $user_id, $upUpHuoFyUser['should_user_id'], $upUpHuoFyUser['freeze_user_id'], $way, $descFyHuo2, 1, $huoTzFy2, $upUpHuoFyUser['bo_balance'], 0, $upUpHuoFyUser['hf'], 1, $upUpHuoFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $upUpHuoFyUser['tz_user_id'])
                                ->inc('user_bo_fy_balance', $_huoTzFy2)
                                ->inc('user_bo_total_fy_balance', $_huoTzFy2)
                                ->update();
                        }
                        //*************************  团长分佣   end ****************************//

                        //*************************  代理分佣   start ****************************//
                        // 4.县代管理费
                        $quFyUser = $this->getDaiLiFy(3, $showUser['user_qu']);
                        if($quFyUser['should_user_id'] != 0){
//                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
                            $huoDlFy3 = $balance * config('default_qu_ratio') / 100; // 分佣金额
                            $_huoDlFy3 = $price * config('default_qu_ratio') / 100; // 分佣金额
                            $descFyHuo3_dl = $showUser['user_real_name'] . '补货款-县管理费' . $fyDesc;

                            $this->insertBoFy($quFyUser['fy_user_id'], $user_id, $quFyUser['should_user_id'], 0, $way, $descFyHuo3_dl, 1, $huoDlFy3, $quFyUser['bo_balance'], 0, $quFyUser['hf'], 2, $quFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $quFyUser['fy_user_id'])
                                ->inc('user_bo_fy_balance', $_huoDlFy3)
                                ->inc('user_bo_total_fy_balance', $_huoDlFy3)
                                ->update();
                        }

                        // 5.市代管理费
                        $shiFyUser = $this->getDaiLiFy(2, $showUser['user_shi']);
                        if($shiFyUser['should_user_id'] != 0){
//                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
                            $huoDlFy2 = $balance * config('default_shi_ratio') / 100; // 分佣金额
                            $_huoDlFy2 = $price * config('default_shi_ratio') / 100; // 分佣金额
                            $descFyHuo2_dl = $showUser['user_real_name'] . '补货款-市管理费' . $fyDesc;

                            $this->insertBoFy($shiFyUser['fy_user_id'], $user_id, $shiFyUser['should_user_id'], 0, $way, $descFyHuo2_dl, 1, $huoDlFy2, $shiFyUser['bo_balance'], 0, $shiFyUser['hf'], 3, $shiFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $shiFyUser['fy_user_id'])
                                ->inc('user_bo_fy_balance', $_huoDlFy2)
                                ->inc('user_bo_total_fy_balance', $_huoDlFy2)
                                ->update();
                        }

                        // 6.省代管理费
                        $shengFyUser = $this->getDaiLiFy(1, $showUser['user_sheng']);
                        if($shengFyUser['should_user_id'] != 0){
//                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
                            $huoDlFy1 = $balance * config('default_sheng_ratio') / 100; // 分佣金额
                            $_huoDlFy1 = $price * config('default_sheng_ratio') / 100; // 分佣金额
                            $descFyHuo1_dl = $showUser['user_real_name'] . '补货款-省管理费' . $fyDesc;

                            $this->insertBoFy($shengFyUser['fy_user_id'], $user_id, $shengFyUser['should_user_id'], 0, $way, $descFyHuo1_dl, 1, $huoDlFy1, $shengFyUser['bo_balance'], 0, $shengFyUser['hf'], 4, $shengFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $shengFyUser['fy_user_id'])
                                ->inc('user_bo_fy_balance', $_huoDlFy1)
                                ->inc('user_bo_total_fy_balance', $_huoDlFy1)
                                ->update();
                        }
                        //*************************  代理分佣   end ****************************//
                    }
                }

                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        if($showUser['user_bo_invite_other']){
            $showUser['superior'] = Db::table('up_u_user')->where('user_invite', $showUser['user_bo_invite_other'])->value('user_real_name');
        }else{
            $showUser['superior'] = '';
        }
        return $this->fetch('', ['user_id' => $user_id, 'user' => $showUser]);
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $user_ids = input('ids');

        $where['user_rule'] = [['=', '3'], ['=', '2,3'], 'or'];
        $where['user_status'] = ['NEQ', 3];
        $where['user_private_worker'] = 1;

        if($user_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_bo_role = input('user_bo_role'); // 1 普通用户  2 自由创业者   3团员  4 团队长
            $user_bo_district_role = input('user_bo_district_role'); // 2 县级运营商  3 市级分公司  4 省级子公司
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间
            $_tzCode = input('tzCode');
            $_tyCode = input('tyCode');

            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 脖脸皮系统等级
            if(isset($user_bo_role) && $user_bo_role != ''){
                $where['user_bo_role'] = $user_bo_role;
            }
            // 脖脸皮地区等级
            if(isset($user_bo_district_role) && $user_bo_district_role != ''){
                if($user_bo_district_role == 1){
                    $where['user_bo_district_role'] = $user_bo_district_role;
                }else{
                    $where['user_bo_district_role'] = ['LIKE', '%,' . $user_bo_district_role . ',%'];
                }
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
            if(isset($_tzCode) && $_tzCode != ''){
                $where['user_tz_code|user_up_tz_code|user_up_up_tz_code'] = ['LIKE', '%' . $_tzCode . '%'];
                $where['user_bo_role'] = 4;
            }
            if(isset($_tyCode) && $_tyCode != ''){
                $where['user_up_tz_code'] = ['LIKE', '%' . $_tyCode . '%'];
            }
        }else{
            if($user_ids == '') return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            $where['user_id'] = ['IN', $user_ids];
        }

        $list = Db::table('up_u_user')
            ->field([
                'user_id',
                'user_username',
                'user_phone',
                'user_bo_role',
                'user_area_str',
                'user_gender',
                'user_time',
                'user_real_name',
                'user_status',
                'user_last_login',
                'user_shop_name',
                'user_address',
                'user_invite',
                'user_bank_username',
                'user_bank_name',
                'user_bankcard_code',
                'user_bo_fy_balance',
                'user_bo_total_fy_balance',
                'user_bo_balance',
                'user_bo_total_balance',
                'user_bo_district_role',
                'user_up_tz_code',
                'user_ty_code',
                'user_up_up_tz_code',
                'user_tz_code',
                'user_teamer_status',
                'user_agency_sheng_status',
                'user_agency_shi_status',
                'user_agency_qu_status'
            ])
            ->where($where)
            ->select();
    
        foreach($list as $k => $v){
            // 手机号
            $list[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 脖脸皮系统身份
            if($v['user_bo_role'] == 1){
                $list[$k]['user_bo_role'] = '普通用户';
            }elseif ($v['user_bo_role'] == 2){
                $list[$k]['user_bo_role'] = '自由创业者';
            }elseif($v['user_bo_role'] == 3){
                $list[$k]['user_bo_role'] = '团员';
            }else{
                $list[$k]['user_bo_role'] = '团队长';
            }
            // 脖脸皮代理身份
            $sheng_status = '/';
            $shi_status = '/';
            $qu_status = '/';
            if($v['user_bo_district_role'] == '1'){
                $district_role = '普通用户';
                $list[$k]['district_role'] = $district_role;
            }else{
                $district_role = '';
                if(strpos($v['user_bo_district_role'], ',2,') !== false){
                    $district_role .= '县级运营商';
                    $qu_status = $v['user_agency_qu_status'] == 1 ? '启用' : '冻结';
                }
                if(strpos($v['user_bo_district_role'], ',3,') !== false){
                    $district_role .= '，市级分公司';
                    $shi_status = $v['user_agency_shi_status'] == 1 ? '启用' : '冻结';
                }
                if(strpos($v['user_bo_district_role'], ',4,') !== false){
                    $district_role .= '，省级子公司';
                    $sheng_status = $v['user_agency_sheng_status'] == 1 ? '启用' : '冻结';
                }
                $list[$k]['district_role'] = trim($district_role, '，');
            }
            $list[$k]['qu_status'] = $qu_status;
            $list[$k]['shi_status'] = $shi_status;
            $list[$k]['sheng_status'] = $sheng_status;
            // 性别
            switch($v['user_gender']){
                case 1:
                    $list[$k]['user_gender'] = '男';
                    break;
                case 2:
                    $list[$k]['user_gender'] = '女';
                    break;
                case 3:
                    $list[$k]['user_gender'] = '未知';
                    break;
            }
            // 用户状态
            $list[$k]['user_status'] = $v['user_status'] == 1 ? '启用' : '冻结';
            // 银行卡
            $list[$k]['user_bankcard_code'] = "\t" . $v['user_bankcard_code'] . "\t";
            // 团员、团队长编号
            if($v['user_bo_role'] == 3){
                $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                $tzCode = '/';
                $teamer_status = '/';
            }elseif($v['user_bo_role'] == 4){
                $tzCode = $v['user_tz_code'];
                if(in_array($v['user_tz_code'], config('already_use'))){
                    $tyCode = '/';
                }else{
                    $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                    $tzCode .= $v['user_up_tz_code'] == -1 ? '' : '_' . $v['user_up_tz_code'];
                    $tzCode .= $v['user_up_up_tz_code'] == -1 ? '' : '_' . $v['user_up_up_tz_code'];
                }
                $teamer_status = $v['user_teamer_status'] == 1 ? '启用' : '冻结';
            }else{
                $tyCode = '/';
                $tzCode = '/';
                $teamer_status = '/';
            }
            $list[$k]['tyCode'] = $tyCode;
            $list[$k]['tzCode'] = $tzCode;
            $list[$k]['user_teamer_status'] = $teamer_status;
        }
    
        $cellname = [
            ['user_username', '昵称', 15, 'LEFT'],
            ['user_phone', '手机号', 18, 'LEFT'],
            ['user_real_name', '姓名', 15, 'LEFT'],
            ['user_bo_role', '系统身份', 12, 'LEFT'],
            ['tzCode', '团队长编号', 12, 'LEFT'],
            ['tyCode', '团员编号', 12, 'LEFT'],
            ['district_role', '代理身份', 12, 'LEFT'],
            ['user_gender', '性别', 10, 'LEFT'],
            ['user_status', '用户状态', 10, 'LEFT'],
            ['user_teamer_status', '团队长状态', 10, 'LEFT'],
            ['qu_status', '县代状态', 10, 'LEFT'],
            ['shi_status', '市代状态', 10, 'LEFT'],
            ['sheng_status', '省代状态', 10, 'LEFT'],
            ['user_area_str', '地区', 40, 'LEFT'],
            ['user_address', '详细地址', 30, 'LEFT'],
            ['user_time', '注册时间', 18, 'LEFT'],
            ['user_last_login', '最后登录时间', 18, 'LEFT'],
            ['user_invite', '邀请码', 15, 'LEFT'],
            ['user_shop_name', '店铺名称', 20, 'LEFT'],
            ['user_bo_total_balance', '总积分', 15, 'LEFT'],
            ['user_bo_balance', '可用积分', 15, 'LEFT'],
            ['user_bo_total_fy_balance', '总分佣', 15, 'LEFT'],
            ['user_bo_fy_balance', '可用分佣', 15, 'LEFT'],
            ['user_bank_name', '开户行', 12, 'LEFT'],
            ['user_bank_username', '开户名', 12, 'LEFT'],
            ['user_bankcard_code', '卡号', 22, 'LEFT']
        ];
    
        $res = exportExcelZhy('脖脸皮用户', 'Bo_member', $cellname, $list);
        return json($res);
    }

    /*
     * 状态
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function userStatus(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field([
                'user_status',
                'user_teamer_status',
                'user_agency_sheng_status',
                'user_agency_shi_status',
                'user_agency_qu_status',
                'user_bo_fy_balance',
                'user_real_name'
            ])
            ->find();
        if(Request::instance()->isPost()){
            $user_status = input('user_status');
            $user_teamer_status = input('teamer_status');
            $user_agency_sheng_status = input('sheng_status');
            $user_agency_shi_status = input('shi_status');
            $user_agency_qu_status = input('qu_status');
            $remark1 = input('remark1');
            $remark2 = input('remark2');
            $remark3 = input('remark3');
            $remark4 = input('remark4');
            $remark5 = input('remark5');

            // 本月
            $thisMonth = date('Y-m-01 00:00:00');
            $company_user = config('company_user');
            $update = [
                'user_id' => $user_id,
                'user_update_time' => date('Y-m-d H:i:s'),
                'user_status' => $user_status,
                'user_teamer_status' => $user_teamer_status,
                'user_agency_sheng_status' => $user_agency_sheng_status,
                'user_agency_shi_status' => $user_agency_shi_status,
                'user_agency_qu_status' => $user_agency_qu_status
            ];

            Db::startTrans();
            try{
                // 更新用户状态
                Db::table('up_u_user')->update($update);

                // 插入启用/冻结操作记录
                if($user_status != $user['user_status']){
                    $this->statusChange($user_id, 1, $user_status, $remark1);
                }
                if($user_teamer_status != $user['user_teamer_status']){
                    $this->statusChange($user_id, 2, $user_teamer_status, $remark2);
                }
                if($user_agency_sheng_status != $user['user_agency_sheng_status']){
                    $this->statusChange($user_id, 3, $user_agency_sheng_status, $remark3);
                }
                if($user_agency_shi_status != $user['user_agency_shi_status']){
                    $this->statusChange($user_id, 4, $user_agency_shi_status, $remark4);
                }
                if($user_agency_qu_status != $user['user_agency_qu_status']){
                    $this->statusChange($user_id, 5, $user_agency_qu_status, $remark5);
                }

                // 团队长
                if($user['user_teamer_status'] == 2 && $user_teamer_status == 1){
                    // ******************************  团队长本人   start **********************//
                    $tzFy = $this->getFreezeFy($user_id, 1, $company_user, $thisMonth);
                    if($tzFy){
                        $fyIds = array_column($tzFy, 'binte_id');
                        $fyPirce = array_column($tzFy, 'binte_price');
                        $totalFy = array_sum($fyPirce);

                        // 将未恢复的设置成已恢复
                        Db::table('up_bo_fy')->where('binte_id', 'IN', $fyIds)->setField('binte_hf', 2);

                        //**************************  本团队长恢复佣金   start   **********************//
                        // 本团长佣金明细
                        $this->insertBoFy($user_id, 0, $user_id, 0, 1, $user['user_real_name'] . '_团队长启用恢复佣金', 1, $totalFy, $user['user_bo_fy_balance'], 0, 2, 1);

                        Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->inc('user_bo_fy_balance', $totalFy)
                            ->inc('user_bo_total_fy_balance', $totalFy)
                            ->update();
                        $user['user_bo_fy_balance'] += $totalFy;
                        //**************************  本团队长恢复佣金   end   **********************//

                        //**************************  公司账号扣除佣金   start   **********************//
                        $company1 = Db::table('up_u_user')->where('user_id', config('company_user'))->field('user_bo_fy_balance')->find();
                        $this->insertBoFy(config('company_user'), $user_id, config('company_user'), 0, 2, $user['user_real_name'] . '_团队长启用扣除佣金', 1, $totalFy, $company1['user_bo_fy_balance'], 0, 2, 0);

                        Db::table('up_u_user')
                            ->where('user_id', config('company_user'))
                            ->dec('user_bo_fy_balance', $totalFy)
                            ->dec('user_bo_total_fy_balance', $totalFy)
                            ->update();
                        //**************************  公司账号扣除佣金   end   **********************//

                    }
                    // ******************************  团队长本人   end **********************//

                    // ****************************  因为我而冻结的  start ************************//
                    $freezeUser = Db::table('up_bo_fy')
                        ->where([
                            'binte_freeze_user_id' => $user_id,
                            'binte_time'           => ['>', $thisMonth],
                            'binte_hf'             => 1,
                            'binte_type'           => 1,
                            'binte_from'           => 1
                        ])
                        ->field('binte_id, binte_price, binte_should_user_id, binte_other_user_id')
                        ->select();
                    if($freezeUser){
                        // 将未恢复的设置成已恢复
                        $upFyIds = array_column($freezeUser, 'binte_id');
                        Db::table('up_bo_fy')->where('binte_id', 'IN', $upFyIds)->setField('binte_hf', 2);

                        // 给每个用户增加佣金&佣金明细
                        $freezeIds = array_unique(array_column($freezeUser, 'binte_should_user_id'));
                        $insertAll = [];
                        $totalDecPrice = 0; // 需要扣除公司账号的佣金值
                        foreach ($freezeIds as $k => $v){
                            $incPrice = 0;

                            if($v != config('company_user')){

                                foreach ($freezeUser as $kk => $vv){
                                    if($vv['binte_should_user_id'] == $v){
                                        $incPrice += $vv['binte_price'];
                                    }
                                }

                                if($incPrice != 0){
                                    $freezeUpUser = Db::table('up_u_user')->where('user_id', $v)->field('user_bo_fy_balance')->find();
                                    $order_number = 'BF_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
                                    $insertAll[$k] = [
                                        'binte_user_id'        => $v,
                                        'binte_other_user_id'  => $company_user,
                                        'binte_number'         => $order_number,
                                        'binte_type'           => 1,
                                        'binte_desc'           => $user['user_real_name'] . '_团队长启用恢复佣金',
                                        'binte_price'          => $incPrice,
                                        'binte_front'          => $freezeUpUser['user_bo_fy_balance'],
                                        'binte_after'          => $freezeUpUser['user_bo_fy_balance'] + $incPrice,
                                        'binte_order_id'       => 0,
                                        'binte_time'           => date('Y-m-d H:i:s'),
                                        'binte_cate'           => 1,
                                        'binte_should_user_id' => $v,
                                        'binte_freeze_user_id' => 0,
                                        'binte_from'           => 1,
                                        'binte_hf'             => 2,
                                        'binte_admin_id'       => session('username')
                                    ];
                                    if($insertAll){
                                        Db::table('up_bo_fy')->insertAll($insertAll);

                                        Db::table('up_u_user')
                                            ->where('user_id', $v)
                                            ->inc('user_bo_fy_balance', $incPrice)
                                            ->inc('user_bo_total_fy_balance', $incPrice)
                                            ->update();
                                    }
                                    $totalDecPrice += $incPrice;
                                }

                            }
                        }
                        //**************************  公司账号扣除佣金   start   **********************//
                        $company2 = Db::table('up_u_user')->where('user_id', config('company_user'))->field('user_bo_fy_balance')->find();
                        $this->insertBoFy(config('company_user'), $user_id, config('company_user'), 0, 2, $user['user_real_name'] . '_团队长启用扣除佣金', 1, $totalDecPrice, $company2['user_bo_fy_balance'], 0, 2, 0);

                        Db::table('up_u_user')
                            ->where('user_id', config('company_user'))
                            ->dec('user_bo_fy_balance', $totalDecPrice)
                            ->dec('user_bo_total_fy_balance', $totalDecPrice)
                            ->update();
                        //**************************  公司账号扣除佣金   end   **********************//

                    }
                    // ****************************  因为我而冻结的  end ************************//
                }

                // 省代
                if($user['user_agency_sheng_status'] == 2 && $user_agency_sheng_status == 1){
                    $shengFy = $this->getFreezeFy($user_id, 4, $company_user, $thisMonth);
                    if($shengFy){
                        $fyIds1 = array_column($shengFy, 'binte_id');
                        $fyPirce1 = array_column($shengFy, 'binte_price');
                        $totalFy1 = array_sum($fyPirce1);

                        // 将未恢复的设置成已恢复
                        Db::table('up_bo_fy')->where('binte_id', 'IN', $fyIds1)->setField('binte_hf', 2);

                        // ********************************   省代恢复佣金   start  *******************//
                        $this->insertBoFy($user_id, 0, $user_id, 0, 1, $user['user_real_name'] . '_省级子公司启用恢复佣金', 1, $totalFy1, $user['user_bo_fy_balance'], 0, 2, 4);

                        Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->inc('user_bo_fy_balance', $totalFy1)
                            ->inc('user_bo_total_fy_balance', $totalFy1)
                            ->update();
                        $user['user_bo_fy_balance'] += $totalFy1;
                        // ********************************   省代恢复佣金   end  *******************//

                        //**************************  公司账号扣除佣金   start   **********************//
                        $company3 = Db::table('up_u_user')->where('user_id', config('company_user'))->field('user_bo_fy_balance')->find();
                        $this->insertBoFy(config('company_user'), $user_id, config('company_user'), 0, 2, $user['user_real_name'] . '_团队长启用扣除佣金', 1, $totalFy1, $company3['user_bo_fy_balance'], 0, 2, 0);

                        Db::table('up_u_user')
                            ->where('user_id', config('company_user'))
                            ->dec('user_bo_fy_balance', $totalFy1)
                            ->dec('user_bo_total_fy_balance', $totalFy1)
                            ->update();
                        //**************************  公司账号扣除佣金   end   **********************//
                    }
                }

                // 市代
                if($user['user_agency_shi_status'] == 2 && $user_agency_shi_status == 1){
                    $shiFy = $this->getFreezeFy($user_id, 3, $company_user, $thisMonth);
                    if($shiFy){
                        $fyIds2 = array_column($shiFy, 'binte_id');
                        $fyPirce2 = array_column($shiFy, 'binte_price');
                        $totalFy2 = array_sum($fyPirce2);

                        // 将未恢复的设置成已恢复
                        Db::table('up_bo_fy')->where('binte_id', 'IN', $fyIds2)->setField('binte_hf', 2);

                        // ********************************   市代恢复佣金   start  *******************//
                        $this->insertBoFy($user_id, 0, $user_id, 0, 1, $user['user_real_name'] . '_市级分公司启用恢复佣金', 1, $totalFy2, $user['user_bo_fy_balance'], 0, 2, 3);

                        Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->inc('user_bo_fy_balance', $totalFy2)
                            ->inc('user_bo_total_fy_balance', $totalFy2)
                            ->update();
                        $user['user_bo_fy_balance'] += $totalFy2;
                        // ********************************   市代恢复佣金   end  *******************//

                        //**************************  公司账号扣除佣金   start   **********************//
                        $company4 = Db::table('up_u_user')->where('user_id', config('company_user'))->field('user_bo_fy_balance')->find();
                        $this->insertBoFy(config('company_user'), $user_id, config('company_user'), 0, 2, $user['user_real_name'] . '_团队长启用扣除佣金', 1, $totalFy2, $company4['user_bo_fy_balance'], 0, 2, 0);

                        Db::table('up_u_user')
                            ->where('user_id', config('company_user'))
                            ->dec('user_bo_fy_balance', $totalFy2)
                            ->dec('user_bo_total_fy_balance', $totalFy2)
                            ->update();
                        //**************************  公司账号扣除佣金   end   **********************//
                    }
                }

                // 县代
                if($user['user_agency_qu_status'] == 2 && $user_agency_qu_status == 1){
                    $xianFy = $this->getFreezeFy($user_id, 2, $company_user, $thisMonth);
                    if($xianFy){
                        $fyIds3 = array_column($xianFy, 'binte_id');
                        $fyPirce3 = array_column($xianFy, 'binte_price');
                        $totalFy3 = array_sum($fyPirce3);

                        // 将未恢复的设置成已恢复
                        Db::table('up_bo_fy')->where('binte_id', 'IN', $fyIds3)->setField('binte_hf', 2);

                        // ********************************   县代恢复佣金   start  *******************//
                        $this->insertBoFy($user_id, 0, $user_id, 0, 1, $user['user_real_name'] . '_县级运营商启用恢复佣金', 1, $totalFy3, $user['user_bo_fy_balance'], 0, 2, 2);

                        Db::table('up_u_user')
                            ->where('user_id', $user_id)
                            ->inc('user_bo_fy_balance', $totalFy3)
                            ->inc('user_bo_total_fy_balance', $totalFy3)
                            ->update();
                        // ********************************   县代恢复佣金   end  *******************//

                        //**************************  公司账号扣除佣金   start   **********************//
                        $company5 = Db::table('up_u_user')->where('user_id', config('company_user'))->field('user_bo_fy_balance')->find();
                        $this->insertBoFy(config('company_user'), $user_id, config('company_user'), 0, 2, $user['user_real_name'] . '_团队长启用扣除佣金', 1, $totalFy3, $company5['user_bo_fy_balance'], 0, 2, 0);

                        Db::table('up_u_user')
                            ->where('user_id', config('company_user'))
                            ->dec('user_bo_fy_balance', $totalFy3)
                            ->dec('user_bo_total_fy_balance', $totalFy3)
                            ->update();
                        //**************************  公司账号扣除佣金   end   **********************//
                    }
                }

                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }

        return $this->fetch('', ['user' => $user, 'user_id' => $user_id]);
    }

    /*
     * 设置代理
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function userDaiLi(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $userProvince = input('province') ?: 0;
            $userCity = input('city') ?: 0;
            $userDistrict = input('district') ?: 0;

            $update = [
                'user_id' => $user_id,
                'user_agency_sheng' => $userProvince,
                'user_agency_shi' => $userCity,
                'user_agency_qu' => $userDistrict,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_u_user')->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }

        }
        $user = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_agency_sheng, user_agency_shi, user_agency_qu')
            ->find();
        $alreadyUse = Db::table('up_u_user')->field('user_agency_sheng, user_agency_shi, user_agency_qu')->select();
        $alreadyProvince = array_column($alreadyUse, 'user_agency_sheng');
        $alreadyCity = array_column($alreadyUse, 'user_agency_shi');
        $alreadyQu = array_column($alreadyUse, 'user_agency_qu');
        $area = Db::table('up_area')->where('level', 'BETWEEN', [1, 3])->field('district_id, district, level')->select();
        $province = [];
        $city = [];
        $district = [];
        foreach ($area as $k => $v){
            if($v['level'] == 1){
                $province[$k] = $v;
            }elseif ($v['level'] == 2){
                $city[$k] = $v;
            }else{
                $district[$k] = $v;
            }
        }
//        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
//        $city = Db::table('up_area')->where('level', 2)->field('district_id, district')->select();
//        $district = Db::table('up_area')->where('level', 3)->field('district_id, district')->select();

        $this->assign([
            'user_id' => $user_id,
            'user' => $user,
            'alreadyProvince' => $alreadyProvince,
            'alreadyCity' => $alreadyCity,
            'alreadyQu' => $alreadyQu,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);
        return $this->fetch();
    }
}